package cz.muni.fi.pa165.dao.impl;

import cz.muni.fi.pa165.dao.PackageDAO;
import cz.muni.fi.pa165.entity.Package;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

/**
 * PackageDAO implemented class
 * @author Jakub Janco
 */
@Stateless
public class PackageDAOImpl implements PackageDAO{

    @PersistenceContext(unitName = "package-unit", type = PersistenceContextType.TRANSACTION)
    //@Inject
    private EntityManager em;
    
    @Override
    public void createPackage(Package pkg) {
        if(pkg == null) {
            throw new IllegalArgumentException("Package cannot be null");
        }
        if(pkg.getId() != null) {
            throw new IllegalArgumentException("Package cannot have id");
        }
        em.persist(pkg);
    }

    @Override
    public void removePackage(Package pkg) {
        checkPackage(pkg);
        em.remove(em.find(Package.class, pkg.getId()));
    }

    @Override
    public void updatePackage(Package pkg) {
        checkPackage(pkg);
        em.merge(pkg);
    }

    @Override
    public Package getPackageById(Long id) {
        if(id == null) {
            throw new IllegalArgumentException("Id cannot be null");
        }
        return em.find(Package.class, id);
    }

    @Override
    public List<Package> getAllPackages() {
        return em.createQuery("SELECT p FROM Package as p").getResultList();//Query("select from Package").getResultList();
    }
    
    private void checkPackage(Package pkg) {
        if(pkg == null) {
            throw new IllegalArgumentException("Package cannot be null");
        }
        if(pkg.getId() == null) {
            throw new IllegalArgumentException("Package ID cannot be null");
        }
    }
}
